layui.use(['element', 'layer', 'form', 'table'], function () {
    var element = layui.element;
    var table = layui.table;
    var layer = layui.layer;
    var form = layui.form;

    var tableInfo = table.render({
        id: 'registerUserInfoTableId',
        elem: '#registerUserInfoTable',
        url: '/admin/registerUser/registerUserInfoDetail',
        method: 'post',
        page: true,
        limit: 10,
        loading: true,
        skin: 'row',
        even: true,
        text: {
            none: '暂无相关数据'
        },
        cols: [[
            {checkbox: true, fixed: true},
            {field: 'id', title: '唯一账号', fixed: 'left'}
            , {field: 'name', title: '昵称', width: 80}
            , {field: 'sex', title: '性别',align: 'center'}
            , {field: 'age', title: '年龄',align: 'center'}
            , {field: 'phone', title: '联系电话',align: 'center'}
            , {field: 'photo', title: '头像', templet:'#show_img', align: 'center'}
            , {field: 'address', title: '地址', align: 'center', width: 80}
            , {field: 'mail', title: '邮件', align: 'center'}
            , {field: 'createTime', title: '注册时间', sort: true, unresize: true, align: 'center'}
            , {fixed: 'right', title: '操作', width: 200, align: 'center', unresize: true, toolbar: '#oreationBtn'}
        ]]
    });

    table.on('tool(registerUserInfoTable)', function (obj) {
        var layEvent = obj.event;
        if (layEvent == 'detail') { //详情
            detailFunction(obj);
        } else if (layEvent === 'del') { //删除
            deleteFunction(obj);
        } else if (layEvent === 'update') { //更新
            updateFunction(obj);
        }
    });

    function detailFunction(obj) {
        var content = $('#userDetailView');
        layer.open({
            type: 1,
            skin: 'layui-layer-molv',
            title: ['唯一账号: '+obj.data.id+" =============  注册时间:  "+obj.data.createTime, 'font-size:18px;'],
            closeBtn: 1,
            shade: 0,
            content: content,
            area: ['100%', '100%'],
            shadeClose: true,
            resize: false,
            anim: 1,
            id: 'LAY_layuidetailsadas',
            moveType: 1,
            maxmin: false,
            success: function (layero, index) {
                $('#openSwitch').prop('checked',false);
                $('#detail_upload_view').hide();
                $('#updateBtnView').hide();
                $('#d_name').val(obj.data.name);
                $('[name="d_sex"][value="'+obj.data.sex+'"]').prop('checked', true);
                $('#d_age').val(obj.data.age);
                $('#d_phone').val(obj.data.phone);
                $('#d_email').val(obj.data.mail);
                $('#d_idCard').val(obj.data.idCard);
                $('#d_address').val(obj.data.address);
                $('#showMyPhoto').attr('src', obj.data.photo);
                form.render();
                form.on('submit(updateUserBtn)', function(data){
                    var params = $.param({
                        id:obj.data.id,
                        name: data.field.d_name,
                        sex: data.field.d_sex,
                        age: data.field.d_age,
                        phone: data.field.d_phone,
                        mail: data.field.d_email,
                        idCard: data.field.d_idCard,
                        address: data.field.d_address
                    }, true);
                    $.ajax({
                        url: '/admin/registerUser/updateOtherProperty',
                        type: 'post',
                        data: params,
                        dataType: 'json',
                        success: function (e) {
                            layer.msg(e.msg);
                            if (e.msg == "修改成功") {
                                layer.close(index);
                                tableInfo.reload({ //执行重载
                                    page: {
                                        curr: 1 //重新从第 1 页开始
                                    },
                                    done: function (res, curr, count) {
                                        this.where = {};
                                    }
                                });
                            }
                        }
                    });
                    return false;
                });
                form.on('switch(isUpdate)', function(data){
                    if (data.elem.checked) {
                        $('#detail_upload_view').show();
                        $('#updateBtnView').show();
                    }else {
                        $('#detail_upload_view').hide();
                        $('#updateBtnView').hide();
                    }
                });
            },
            cancel: function (index, layero) {

            }
         })
    }

    function deleteFunction(obj) {
        layer.open({
            type: 1,
            title: false,
            closeBtn: 2,
            resize: true,
            content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">' +
            '(请慎重)是否需要删除?删除后将不可恢复</div>',
            area: '30%',
            shade: 0.8,
            shadeClose: true,
            anim: 1,
            id: 'LAY_layuiprodel',
            btn: ['绝不后悔', '我怂了'],
            moveType: 1,
            yes: function (index, layero) {
                var params = $.param({
                    id: obj.data.id
                }, true);
                $.ajax({
                    url: '/admin/registerUser/deleteById',
                    type: 'post',
                    data: params,
                    dataType: 'json',
                    success: function (e) {
                        layer.msg(e.msg);
                        layer.close(index);
                        if (e.msg == "删除成功") {
                            obj.del();
                        }
                    }
                })
            }
        });
    }

    function updateFunction(obj) {
        var content = $('#updatePassWordInfo');
        layer.open({
            type: 1,
            skin: 'layui-layer-molv',
            title: ['更新密码', 'font-size:18px;'],
            closeBtn: 1,
            shade: 0.3,
            content: content,
            area: ['30%', '30%'],
            shadeClose: true,
            resize: true,
            anim: 1,
            id: 'LAY_layuiroupdate', //设定一个id，防止重复弹出
            moveType: 1,
            maxmin: false,
            success: function (layero, index) {
                $('#password').val('');
                var active = {
                    updatePassword:function () {
                        var password = $('#newpassword').val();
                        if (password == '') {
                            layer.msg("未做任何修改");
                            return false;
                        }
                        var params = $.param({
                            id:obj.data.id,
                            password:password
                        }, true);
                        $.ajax({
                            url: '/admin/registerUser/updatePwd',
                            type: 'post',
                            data: params,
                            dataType: 'json',
                            success: function (e) {
                                layer.msg(e.msg);
                                if (e.msg == "密码修改成功")
                                    layer.close(index);
                            }
                        })
                    }
                };
                $('.updatePassword .layui-btn').on('click', function () {
                    var type = $(this).data('type');
                    active[type] ? active[type].call(this) : '';
                });
            },
            cancel: function (index, layero) {
                $('#newpassword').val('');
            }
        });
    }

    var active = {
        findRegisterUserInfo:function () {
            var content = $('#findByProperty');
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: ['查询维度', 'font-size:18px;'],
                closeBtn: 1,
                shade: 0.3,
                content: content,
                area: ['70%', '80%'],
                shadeClose: false,
                resize: true,
                anim: 1,
                id: 'LAY_layuirofindproperty', //设定一个id，防止重复弹出
                moveType: 1,
                maxmin: false,
                success: function (layero, index) {
                    $('#myid').val('');
                    $('#myname').val('');
                    $('[name="mysex"][value=""]').prop('checked', true);
                    $('#minage').val('');
                    $('#maxage').val('');
                    $('#myphone').val('');
                    $('#myemail').val('');
                    $('#myidCard').val('');
                    $('#myaddress').val('');
                    $('#createTimeScope').val('');
                    form.render();
                    var active = {
                        findInfoByProperty:function () {
                            var id =  $('#myid').val();
                            var name =  $('#myname').val();
                            var sex = $('input[name="mysex"]:checked').val();
                            var minAge =  $('#minage').val();
                            var maxAge =  $('#maxage').val();
                            var phone =  $('#myphone').val();
                            var mail =  $('#myemail').val();
                            var idCard =  $('#myidCard').val();
                            var address =  $('#myaddress').val();
                            var createTime =  $('#createTimeScope').val();
                            var params ={
                                id: id,
                                name: name,
                                sex: sex,
                                minAge: minAge,
                                maxAge: maxAge,
                                phone: phone,
                                address: address,
                                mail: mail,
                                idCard: idCard,
                                createTime: createTime
                            };
                            tableInfo.reload({
                                where: {
                                    key: JSON.stringify(params) //转成json
                                },
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                },
                                done: function (res, curr, count) {
                                    this.where = {};
                                    layer.close(index);
                                }
                            });
                        }
                    };
                    $('.findByPropertyBtn .layui-btn').on('click', function () {
                        var type = $(this).data('type');
                        active[type] ? active[type].call(this) : '';
                    });
                },
                cancel: function(index, layero){
                    $('#myid').val('');
                    $('#myname').val('');
                    $('[name="mysex"][value=""]').prop('checked', true);
                    $('#minage').val('');
                    $('#maxage').val('');
                    $('#myphone').val('');
                    $('#myemail').val('');
                    $('#myidCard').val('');
                    $('#myaddress').val('');
                    $('#createTimeScope').val('');
                    form.render();
                }
            })
        },
        deletebatchInfo:function () {
            var checkStatus = table.checkStatus('registerUserInfoTableId')
                , data = checkStatus.data;
            if (data.length > 50) {
                layer.msg("超过最大数量限制");
                return false;
            }
            layer.open({
                type: 1,
                title: false,
                closeBtn: 2,
                resize: true,
                content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">' +
                '是否需要删除?删除后将不可恢复</div>',
                area: '30%',
                shade: 0.8,
                shadeClose: true,
                anim: 1,
                id: 'LAY_layuiprodel', //设定一个id，防止重复弹出
                btn: ['绝不后悔', '我怂了'],
                moveType: 1,
                yes: function (index, layero) {
                    var params = $.param({
                        mydata: JSON.stringify(data)
                    }, true);
                    $.ajax({
                        url: '/admin/registerUser/deleteBatchById',
                        type: 'post',
                        data: params,
                        dataType: 'json',
                        success: function (e) {
                            layer.msg(e.msg);
                            layer.close(index);
                            if (e.msg == "删除成功") {
                                tableInfo.reload({ //执行重载
                                    page: {
                                        curr: 1 //重新从第 1 页开始
                                    },
                                    done: function (res, curr, count) {
                                        this.where = {};
                                    }
                                });
                            }
                        }
                    })
                }
            });
        }
    };

    $('.AllBtnController .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    //添加用户
    form.on('submit(addUserBtn)', function(data){
        var params = $.param({
            mydata: JSON.stringify(data.field)
        }, true);
        $.ajax({
            url: '/admin/registerUser/addOneRegisterUser',
            type: 'post',
            data: params,
            dataType: 'json',
            success: function (e) {
                layer.msg(e.msg);
                if (e.msg == "添加成功") {
                    tableInfo.reload({ //执行重载
                        page: {
                            curr: 1 //重新从第 1 页开始
                        },
                        done: function (res, curr, count) {
                            this.where = {};
                        }
                    });
                }
            }
        });
        return false;
    });

    layui.use('upload', function(){
        var $ = layui.jquery,upload = layui.upload;
        upload.render({
            elem:'#uploadMyphoto',
            url:'/admin/registerUser/upload',
            accept:'images',
            auto: false,
            bindAction:'#confirmMyphoto',
            choose:function(obj) {
                obj.preview(function(index, file, result){
                    $('#showphoto').attr('src', result);
                });
            },
            done: function(res, index, upload){
                if (res.code != 0)
                    layer.msg('上传失败');
                else
                    layer.msg('上传成功');
            }
        })
    });

    layui.use('upload', function(){
        var $ = layui.jquery,upload = layui.upload;
        upload.render({
            elem:'#d_uploadMyphoto',
            url:'/admin/registerUser/upload',
            accept:'images',
            auto: false,
            bindAction:'#d_confirmMyphoto',
            choose:function(obj) {
                obj.preview(function(index, file, result){
                    $('#d_showphoto').attr('src', result);
                });
            },
            done: function(res, index, upload){
                if (res.code != 0)
                    layer.msg('上传失败');
                else {
                    layer.msg('上传成功');
                    $('#showMyPhoto').attr('src', res.data.access_url);
                }
            }
        })
    });

    layui.use('laydate', function () {
        var laydate = layui.laydate;
        laydate.render({
            elem: '#createTimeScope',
            type: 'datetime',
            range: true,
            format: 'yyyy-MM-dd HH:mm:ss',
            calendar: true
        });
    });

});